package com.bjc.base.handler;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bjc.base.bean.request.UserReqVO;
import com.bjc.base.bean.response.UserVO;
import com.bjc.base.builder.TextBuilder;
import com.bjc.base.service.IUserService;
import com.bjc.base.utils.UserReqVOAndWxMpUser;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class SubscribeHandler extends AbstractHandler {

	String msg = "幼儿阶段是阅读习惯养成的黄金期，也是财商培养的启蒙和关键期！\n" + 
			"犹太民族人才辈出就是因为他们从小重视孩子阅读习惯和财商的培养。\n" + 
			"\n" + 
			"小鱼儿共享绘本，一个专注培养幼儿良好阅读习惯并进行财商实践的平台！\n" + 
			" \n" + 
			"这里是一群热爱阅读和追求高品质育儿的父母们组成的成长大本营；\n" + 
			"加绘本助理拉您进群，助理微信：bj18010039827\n" + 
			"在这里，可以咨询绘本借阅和分享；\n" + 
			"在这里，可以享受亲子教育专家的指导；\n" + 
			"在这里，及时获取最新活动资讯！\n" + 
			" \n" + 
			"还有诸多福利等您拿。\n" + 
			" \n" + 
			" 回复“借阅地点”，查看所有借阅驿站；\n" + 
			" 回复“借阅绘本”，查看借阅流程；\n" + 
			" 回复“分享绘本”，查看绘本分享流程；\n" + 
			" 回复“选择绘本”，查看选择绘本攻略；\n" + 
			" 回复“免费活动”，查看参加活动详情；\n" + 
			" 回复“其他”，联系小鱼儿助理，为您答疑解惑。\n" + 
			"\n" + 
			"爱阅读，爱分享；\n" + 
			"小鱼儿陪伴孩子快乐成长！ [Heart] [Heart]";
	
	@Autowired
	private IUserService userService;

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) throws WxErrorException {

		this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

		// 获取微信用户基本信息
		//String lang = "zh_CN"; // 语言
		WxMpUser userWxInfo = wxMpService.getUserService().userInfo(wxMessage.getFromUser(), null);

		if (userWxInfo != null) {
			UserReqVO reqVO = new UserReqVO();
			reqVO.setOpenid(userWxInfo.getOpenId());
			UserVO user = userService.get(reqVO);
			UserReqVOAndWxMpUser.setUserReqVOByWxMpUser(reqVO, userWxInfo);
			if(user == null) {
				userService.insert(reqVO);
			}else {
				userService.update(reqVO);
			}
		}

		WxMpXmlOutMessage responseResult = null;
		try {
			responseResult = handleSpecial(wxMessage);
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
		}

		if (responseResult != null) {
			return responseResult;
		}

		try {
			return new TextBuilder().build(msg, wxMessage, wxMpService);
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
		}

		return null;
	}

	/**
	 * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
	 */
	private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage) throws Exception {
		// TODO
		return null;
	}

}
